package com.educatioin.manage.web.studytours.controller;

import com.educatioin.commons.util.AjaxResult;
import com.educatioin.manage.common.beans.Response;
import com.educatioin.manage.web.studytours.entity.StudyAbroadProductEntity;
import com.educatioin.manage.web.studytours.po.StudyAbroadProductPo;
import com.educatioin.manage.web.studytours.repository.StudyAbroadProductRepository;
import com.educatioin.manage.web.studytours.request.QueryStudyAbroadProductsReq;
import com.educatioin.manage.web.studytours.response.QueryStudyAbroadProductsRsp;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Predicate;
import java.util.List;

/**
 * Created by zhangchen on 2018/3/5.
 */
@RestController
@RequestMapping(value = {"/api/studyAbroad"})
public class StudyAbroadController {

    @Autowired
    private StudyAbroadProductRepository studyAbroadProductRepository;

    /**
     * 分页查询留学产品列表
     * @param queryStudyAbroadProductsReq
     * @return
     */
    @RequestMapping("/queryStudyAbroadProducts")
    @ResponseBody
    public QueryStudyAbroadProductsRsp queryStudyAbroadProducts(QueryStudyAbroadProductsReq queryStudyAbroadProductsReq) {
        QueryStudyAbroadProductsRsp queryStudyAbroadProductsRsp = new QueryStudyAbroadProductsRsp();

        Integer page = queryStudyAbroadProductsReq.getPage();
        Integer limit = queryStudyAbroadProductsReq.getLimit();
        if(null == page || page <= 0 || null == limit || limit <= 0){
            queryStudyAbroadProductsRsp.setReturnCode(Response.RETURN_FAIL_CODE);
            queryStudyAbroadProductsRsp.setReturnMsg("分页查询错误！");
            return queryStudyAbroadProductsRsp;
        }

        if(page > 0) {
            page = page -1;
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageRequest = new PageRequest(page, limit, sort);

        String name = queryStudyAbroadProductsReq.getName();
        String generation = queryStudyAbroadProductsReq.getGeneration();
        String country = queryStudyAbroadProductsReq.getCountry();

        Page<StudyAbroadProductPo> retPage = studyAbroadProductRepository.findAll((root, query, cb) -> {
            List<Predicate> predicates = Lists.newArrayList();
            if(StringUtils.isNoneBlank(name)) {
                predicates.add(cb.and(cb.like(root.get("name"), name)));
            }
            if(StringUtils.isNoneBlank(generation)) {
                predicates.add(cb.and(cb.like(root.get("generation"), generation)));
            }
            if(StringUtils.isNoneBlank(country)) {
                predicates.add(cb.and(cb.like(root.get("country"), country)));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        queryStudyAbroadProductsRsp.setReturnCode(Response.RETURN_SUCCESS_CODE);
        if(retPage.hasContent()) {
            List<StudyAbroadProductEntity> studyAbroadProductEntities = Lists.newArrayList();
            for(StudyAbroadProductPo studyAbroadProductPo : retPage.getContent()){
                StudyAbroadProductEntity studyAbroadProductEntity = new StudyAbroadProductEntity();
                studyAbroadProductEntity.setId(studyAbroadProductPo.getId());
                studyAbroadProductEntity.setCode(studyAbroadProductPo.getCode());
                studyAbroadProductEntity.setCountry(studyAbroadProductPo.getCountry());
                studyAbroadProductEntity.setDeposit(studyAbroadProductPo.getDeposit());
                studyAbroadProductEntity.setGeneration(studyAbroadProductPo.getGeneration());
                studyAbroadProductEntity.setName(studyAbroadProductPo.getName());
                studyAbroadProductEntity.setPrice(studyAbroadProductPo.getPrice());
                studyAbroadProductEntities.add(studyAbroadProductEntity);
            }
            queryStudyAbroadProductsRsp.setData(studyAbroadProductEntities);
        }
        queryStudyAbroadProductsRsp.setCount((int)retPage.getTotalElements());
        return queryStudyAbroadProductsRsp;
    }

    /**
     * 同步留学产品（新增、编辑）
     * @param studyAbroadProductPo
     * @return
     */
    @RequestMapping("/sync")
    @ResponseBody
    public AjaxResult<String> syncStudyAbroadProduct(@RequestBody StudyAbroadProductPo studyAbroadProductPo) {
        AjaxResult<String> result = new AjaxResult<>();

        if(studyAbroadProductPo.getId() != null) {
            StudyAbroadProductPo dbStudyAbroadProductPo = studyAbroadProductRepository.findOne(studyAbroadProductPo.getId());
            dbStudyAbroadProductPo.setName(studyAbroadProductPo.getName());
            dbStudyAbroadProductPo.setShowImage(studyAbroadProductPo.getShowImage());
            dbStudyAbroadProductPo.setCode(studyAbroadProductPo.getCode());
            dbStudyAbroadProductPo.setGeneration(studyAbroadProductPo.getGeneration());
            dbStudyAbroadProductPo.setCountry(studyAbroadProductPo.getCountry());
            dbStudyAbroadProductPo.setPrice(studyAbroadProductPo.getPrice());
            dbStudyAbroadProductPo.setDeposit(studyAbroadProductPo.getDeposit());
            dbStudyAbroadProductPo.setDetail(studyAbroadProductPo.getDetail());
            dbStudyAbroadProductPo.setSchedule(studyAbroadProductPo.getSchedule());
            dbStudyAbroadProductPo.setDescription(studyAbroadProductPo.getDescription());

            StudyAbroadProductPo resp = studyAbroadProductRepository.save(dbStudyAbroadProductPo);
            if(resp == null) {
                result.setCode(AjaxResult.ERROR_CODE);
                result.setMsg("更新留学产品失败");
                return result;
            }
        } else {
            StudyAbroadProductPo resp = studyAbroadProductRepository.save(studyAbroadProductPo);
            if(resp == null) {
                result.setCode(AjaxResult.ERROR_CODE);
                result.setMsg("新增留学产品失败");
                return result;
            }
        }
        return result;
    }

    /**
     * 删除留学产品（单个）
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult<String> deleteStudyToursProduct(Long id) {
        AjaxResult<String> result = new AjaxResult<>();
        StudyAbroadProductPo studyAbroadProductPo = studyAbroadProductRepository.findOne(id);
        if(null == studyAbroadProductPo){
            result.setCode(AjaxResult.ERROR_CODE);
            result.setMsg("找不到删除对象！");
            return result;
        }

        studyAbroadProductRepository.delete(studyAbroadProductPo);
        result.setCode(AjaxResult.SUCCESS_CODE);
        result.setMsg("删除成功");
        return result;
    }

    /**
     * 获取留学产品详情
     * @param studyToursProductId
     * @return
     */
    @RequestMapping("/detail")
    @ResponseBody
    public AjaxResult<StudyAbroadProductPo> findById(Long studyToursProductId) {
        AjaxResult<StudyAbroadProductPo> ar = new AjaxResult<>();

        StudyAbroadProductPo studyAbroadProductPo = studyAbroadProductRepository.findOne(studyToursProductId);

        if(null == studyAbroadProductPo){
            ar.setCode(AjaxResult.ERROR_CODE);
            ar.setMsg("留学产品不存在！");
            return ar;
        }

        ar.setCode(AjaxResult.SUCCESS_CODE);
        ar.setData(studyAbroadProductPo);
        return ar;
    }
}
